/**
 * 本地存储工具函数
 */

import { STORAGE_KEYS } from '../constants/common';

/**
 * 本地存储操作类
 */
export class StorageUtil {
  /**
   * 设置本地存储
   */
  static set(key: string, value: any): void {
    try {
      const serializedValue = JSON.stringify(value);
      localStorage.setItem(key, serializedValue);
    } catch (error) {
      console.error('Storage set error:', error);
    }
  }

  /**
   * 获取本地存储
   */
  static get<T = any>(key: string, defaultValue?: T): T | null {
    try {
      const item = localStorage.getItem(key);
      if (item === null) {
        return defaultValue || null;
      }
      return JSON.parse(item) as T;
    } catch (error) {
      console.error('Storage get error:', error);
      return defaultValue || null;
    }
  }

  /**
   * 移除本地存储
   */
  static remove(key: string): void {
    try {
      localStorage.removeItem(key);
    } catch (error) {
      console.error('Storage remove error:', error);
    }
  }

  /**
   * 清空本地存储
   */
  static clear(): void {
    try {
      localStorage.clear();
    } catch (error) {
      console.error('Storage clear error:', error);
    }
  }

  /**
   * 检查是否支持本地存储
   */
  static isSupported(): boolean {
    try {
      const testKey = '__storage_test__';
      localStorage.setItem(testKey, 'test');
      localStorage.removeItem(testKey);
      return true;
    } catch {
      return false;
    }
  }

  /**
   * 获取存储大小
   */
  static getSize(): number {
    let total = 0;
    for (const key in localStorage) {
      if (localStorage.hasOwnProperty(key)) {
        total += localStorage[key].length + key.length;
      }
    }
    return total;
  }
}

/**
 * Session存储操作类
 */
export class SessionStorageUtil {
  /**
   * 设置会话存储
   */
  static set(key: string, value: any): void {
    try {
      const serializedValue = JSON.stringify(value);
      sessionStorage.setItem(key, serializedValue);
    } catch (error) {
      console.error('SessionStorage set error:', error);
    }
  }

  /**
   * 获取会话存储
   */
  static get<T = any>(key: string, defaultValue?: T): T | null {
    try {
      const item = sessionStorage.getItem(key);
      if (item === null) {
        return defaultValue || null;
      }
      return JSON.parse(item) as T;
    } catch (error) {
      console.error('SessionStorage get error:', error);
      return defaultValue || null;
    }
  }

  /**
   * 移除会话存储
   */
  static remove(key: string): void {
    try {
      sessionStorage.removeItem(key);
    } catch (error) {
      console.error('SessionStorage remove error:', error);
    }
  }

  /**
   * 清空会话存储
   */
  static clear(): void {
    try {
      sessionStorage.clear();
    } catch (error) {
      console.error('SessionStorage clear error:', error);
    }
  }
}

/**
 * 应用专用存储工具
 */
export const appStorage = {
  // 用户相关
  setUser: (user: any) => StorageUtil.set(STORAGE_KEYS.USER, user),
  getUser: () => StorageUtil.get(STORAGE_KEYS.USER),
  removeUser: () => StorageUtil.remove(STORAGE_KEYS.USER),

  // Token相关
  setToken: (token: string) => StorageUtil.set(STORAGE_KEYS.TOKEN, token),
  getToken: () => StorageUtil.get<string>(STORAGE_KEYS.TOKEN),
  removeToken: () => StorageUtil.remove(STORAGE_KEYS.TOKEN),

  // 租户相关
  setTenant: (tenant: any) => StorageUtil.set(STORAGE_KEYS.TENANT, tenant),
  getTenant: () => StorageUtil.get(STORAGE_KEYS.TENANT),
  removeTenant: () => StorageUtil.remove(STORAGE_KEYS.TENANT),

  // 平台用户相关
  setPlatformUser: (user: any) => StorageUtil.set(STORAGE_KEYS.PLATFORM_USER, user),
  getPlatformUser: () => StorageUtil.get(STORAGE_KEYS.PLATFORM_USER),
  removePlatformUser: () => StorageUtil.remove(STORAGE_KEYS.PLATFORM_USER),

  // 平台Token相关
  setPlatformToken: (token: string) => StorageUtil.set(STORAGE_KEYS.PLATFORM_TOKEN, token),
  getPlatformToken: () => StorageUtil.get<string>(STORAGE_KEYS.PLATFORM_TOKEN),
  removePlatformToken: () => StorageUtil.remove(STORAGE_KEYS.PLATFORM_TOKEN),

  // 主题相关
  setTheme: (theme: string) => StorageUtil.set(STORAGE_KEYS.THEME, theme),
  getTheme: () => StorageUtil.get<string>(STORAGE_KEYS.THEME, 'light'),

  // 语言相关
  setLanguage: (language: string) => StorageUtil.set(STORAGE_KEYS.LANGUAGE, language),
  getLanguage: () => StorageUtil.get<string>(STORAGE_KEYS.LANGUAGE, 'zh-CN'),

  // 侧边栏状态
  setSidebarCollapsed: (collapsed: boolean) => StorageUtil.set(STORAGE_KEYS.SIDEBAR_COLLAPSED, collapsed),
  getSidebarCollapsed: () => StorageUtil.get<boolean>(STORAGE_KEYS.SIDEBAR_COLLAPSED, false),

  // 清除所有应用数据
  clearAll: () => {
    Object.values(STORAGE_KEYS).forEach(key => {
      StorageUtil.remove(key);
    });
  },
};

/**
 * Cookie操作工具
 */
export const cookieUtil = {
  /**
   * 设置Cookie
   */
  set: (name: string, value: string, days = 7): void => {
    const expires = new Date();
    expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
  },

  /**
   * 获取Cookie
   */
  get: (name: string): string | null => {
    const nameEQ = name + '=';
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  },

  /**
   * 删除Cookie
   */
  remove: (name: string): void => {
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;`;
  },
}; 